package com.smh.demo1.a28;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import java.nio.charset.StandardCharsets;

/**
 * @author shiminghui
 * @date 2025/5/3 17:10
 * @description: TODO
 */
public class A28 {
    public static void main(String[] args) throws NoSuchMethodException {
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class);
        //ExceptionHandlerExceptionResolver初始化时会查找所有带ControllerAdvice注解的Bean,然后从Bean里面找有没有异常处理方法,添加到缓存中
        ExceptionHandlerExceptionResolver resolver = context.getBean("exceptionHandlerExceptionResolver", ExceptionHandlerExceptionResolver.class);

        HandlerMethod handlerMethod = new HandlerMethod(new Controller1(), Controller1.class.getMethod("foo"));

        // 可以看到虽然Controller类里面没有异常处理方法,但是异常还是被处理了, 就是被全局的异常处理方法处理了
        resolver.resolveException(request, response, handlerMethod, new ArithmeticException("被零除"));

        System.out.println(new String(response.getContentAsByteArray(), StandardCharsets.UTF_8));


    }
}
